//使用雪碧图作为背景图片的 mixin 方法
import 'package:flutter/cupertino.dart';

mixin SpriteBg {
  //雪碧图里面每个图标的宽度数组
  List<double> itemWidthList = [];
  int index = 0;
  double iconHeight = 0;
  String assetName = "";

  ///flutter使用雪碧图参考 https://blog.wzdxy.com/2019/09/flutter-alignment/
  Map<String, double> getLevelStyle() {
    double totalWidth = 0; // 图片总宽度
    double positionX = 0; // 图片左边的位置
    double width = 0; // 当前等级图片的宽度
    int i;
    // 循环计算出 整个图片的宽度 和 需要的图片所在位置
    for (i = 0; i < itemWidthList.length; i++) {
      if (i < index) positionX += itemWidthList[i];
      if (i == index) width = itemWidthList[i];
      totalWidth += itemWidthList[i];
    }
    // 初始状态(图片和容器中心点重合) 图片左边界到容器左边界的距离, 即 d2
    double zeroPosition = totalWidth / 2 - width / 2;
    // 目标状态时, 图片的偏移量, 即 d1
    double distanceToCenter = positionX - zeroPosition;
    // x = d1/d2
    double alignmentX = (distanceToCenter / zeroPosition);
    return {"x": alignmentX, "width": width};
  }

  Widget build(BuildContext context) {
    var param = getLevelStyle();
    double x = param["x"]!, iconWidth = param['width']!;
    return Container(
        width: iconWidth,
        height: iconHeight,
        margin: const EdgeInsets.only(bottom: 0),
        padding: const EdgeInsets.all(0),
        decoration: BoxDecoration(
            image: DecorationImage(
                image: AssetImage(assetName),
                fit: BoxFit.fitHeight,
                alignment: Alignment(x, 0))));
  }
}
